from django.shortcuts import render,HttpResponse,redirect
from django.http import JsonResponse
from deploy import models
from conf import config
import os
import jenkins
import json
import time
def deploy_web(request):
    if not request.session.get("user_id", None):
        return  redirect("/users/login")
    return render(request,"deploy.html")

def plugin(request):
    if not request.session.get("user_id", None):
        return  redirect("/users/login")
    return render(request,"deploy.html")

#更新插件
def update_plugin(request):
    if not request.session.get("user_id", None):
        return  redirect("/users/login")
    if request.method == "POST":
        name = request.body.decode()
        job_name = name.replace("<span style='color: red;font-weight:bold'>", '').replace("</span>", '')
        jenkins_server_url=config.env["jenkins_server_url"]
        user_id =config.env["user_id"]
        api_token=config.env["api_token"]
        server = jenkins.Jenkins(jenkins_server_url, username=user_id, password=api_token)
        server.build_job(job_name)
        build_number=server.get_job_info(job_name)['lastBuild']['number']+1
        log_data=None
        while True:
            res = os.popen(
                "curl -X GET {}/job/{}/{}/consoleText  --user {}:{}".format(
                    jenkins_server_url, job_name, build_number,user_id,api_token))
            log_data=res.readlines()
            if "SUCCESS" in log_data[-1] or "FAILURE" in log_data[-1]:
                models.Deploy_plugin.objects.filter(name=job_name).update(log=json.dumps(log_data))
                break
        print(log_data[-1])
        if  "SUCCESS" in log_data[-1] :
             redata= {"code": 200, "msg": "更新成功！"}
        else:
            redata = {"code": 599, "msg": "更新失败，请联系管理员！"}
        return JsonResponse(redata,safe=False)


def check_log(request):
    if not request.session.get("user_id", None):
        return  redirect("/users/login")
    if request.method == "POST":
        name=request.body.decode()
        job_name = name.replace("<span style='color: red;font-weight:bold'>",'').replace("</span>",'')
        msgs=json.loads(models.Deploy_plugin.objects.filter(name=job_name)[0].log)
        msg = ''
        for l in msgs:
            s = "<p style='background-color: black;color: white'>{}</p>".format(l)
            msg = msg + s
        redata = {"code": 200, "msg": msg}
        return JsonResponse(redata, safe=False)

def jsondata(request):
    objs=models.Deploy_plugin.objects.all()
    data=list()
    for m in objs:
        d = dict()
        d["id"] = m.id
        d["name"] = "<span style='color: red;font-weight:bold'>%s</span>" % (m.name)
        d['version'] = m.version
        d['env']= m.env
        d['log']=m.log
        data.append(d)
    redata = {"code": 0, "msg": "", "count": len(data), "data": data}
    return JsonResponse(redata, safe=False)

def searchplugin(request):
    query=request.GET.get("query",default=None)
    objs = models.Deploy_plugin.objects.all()
    data = list()
    for m in objs:
        d = dict()
        d["id"] = m.id
        d["name"] = "<span style='color: red;font-weight:bold'>%s</span>" % (m.name)
        d['version'] = m.version
        d['env'] = m.env
        d['log'] = m.log
        if query in str(d):
            data.append(d)
    redata = {"code": 0, "msg": "", "count": len(data), "data": data}
    return JsonResponse(redata, safe=False)